<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : Core Controller
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class MY_Controller extends CI_Controller {

  var $current_user = NULL;
  var $is_admin = FALSE;
  var $is_committe = FALSE;
  var $is_semicolon = FALSE;

  public function __construct() {
    parent::__construct();

    // Setting all time to india.
    date_default_timezone_set('Asia/Calcutta');

    // Enable or Diable profiler
    $this->output->enable_profiler(FALSE);

    // Setting headers
    $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
    $this->output->set_header("Pragma: no-cache");

    // Loading required libraries
    $this->load->library(array('session', 'user_agent', 'user_session', 'crypt'));

    // Checking weather the request is using browser.
    if (!$this->agent->is_browser()) {
      die('Need a browser, buddy :p');
      return;
    }

    // Loading cache driver (APC) | APC Must be installed
    //$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
    //
    // If APC Not Installed
    $this->load->driver('cache', array('adapter' => 'file'));

    // Blocking crawler attack :D
    // If user continously posted a form more than 3 time within 10 sec,
    // the form submit will fail & redirect back to same page
    $attempt_count = 0;
    $last_post_time = NULL;
    if ($this->is_post() && !$this->is_ajax()) {
      $attempt_count = $this->session->userdata('attempt_count');
      $last_post_time = $this->session->userdata('last_post_time');
      if (!empty($attempt_count) && is_numeric($attempt_count)) {
        $this->session->set_userdata('attempt_count', $attempt_count + 1);
      } else {
        $this->session->set_userdata('attempt_count', 1);
      }
      $this->session->set_userdata('last_post_time', time());
      if (!empty($last_post_time) && is_numeric($last_post_time) && (((time() - $last_post_time)) <= 10) && ($attempt_count >= 3)) {
        $this->session->set_flashdata('crawler_warning', 'YES');
        $log_msg = 'page "' . str_replace(site_url(), '/', $this->agent->referrer()) . '" by ' . $this->input->ip_address() . ' on ' . $this->agent->platform() . ' ' . $this->agent->browser() . ' ' . $this->agent->version();
        system_log('crawler', $log_msg);
        redirect($this->agent->referrer());
        return;
      }
      if (!((time() - $last_post_time) <= 10)) {
        $this->session->set_userdata('attempt_count', 1);
      }
    }
  }

  // Check the request type is post
  public function is_post() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      return TRUE;
    } else {
      return FALSE;
    }
  }

  // Check the request type is ajax
  public function is_ajax() {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest") {
      return TRUE;
    } else {
      return FALSE;
    }
  }

  // Clean the user inputs
  public function sanitize($data) {
    return trim(htmlentities(strip_tags($data), ENT_QUOTES, "UTF-8"));
  }

  // Clean input from wsying text editor
  public function sanitize_html($data) {
    $data = preg_replace('/(<br>)+$/', '', $data);
    return trim(strip_tags($data, '<p><b><i><u><a><ul><ol><li><img><h1><h2><h3><h4><h5><h6><blockquote><br>'));
  }

  // Clean and return only alphanumeric string
  public function clean_alphanumeric($data) {
    return trim(preg_replace("/[^a-zA-Z0-9]+/", "", $data));
  }

  // loading a view including header & footer
  public function load_view($view, $vars = array()) {
    $this->load->view('header', $vars);
    $this->load->view($view, $vars);
    $this->load->view('footer');
  }

  // Validating the submit [Against crawlers]
  // (Currently not using due to some issues in session flash data)
  private function validate_csrf() {
    if ($this->is_post() && !$this->is_ajax()) {
      if (check_csrf_token()) {
        return TRUE;
      } else {
        redirect();
      }
    }
  }

}

// Validating the user
// The extended controllers can be accessed only by signed in users.
// If everything fine, '$this->current_user' contains the current user details. 
// and can be used anywhere. else null.
class AUTH_Controller extends MY_Controller {

  public function __construct() {
    parent::__construct();
    $signuser = $this->user_session->signuser();
    if (!empty($signuser)) {
      $this->current_user = $signuser;

      // Setting admin user
      $admin_users = $this->config->item('admins');
      if (!empty($admin_users) && is_array($admin_users)) {
        if (in_array($this->current_user['user_name'], $admin_users)) {
          $this->is_admin = TRUE;
        }
      }

      // Comitte members
      $committee_users = $this->config->item('comittee_members');
      if (!empty($committee_users) && is_array($committee_users)) {
        if (in_array($this->current_user['user_name'], $committee_users)) {
          $this->is_committe = TRUE;
        }
      }

      // Semicolon members
      $semicolon_users = $this->config->item('semicolon_members');
      if (!empty($semicolon_users) && is_array($semicolon_users)) {
        if (in_array($this->current_user['user_name'], $semicolon_users)) {
          $this->is_semicolon = TRUE;
        }
      }
    } else {
      $this->current_user = NULL;
      $this->is_admin = FALSE;
      $this->user_session->signout();
      $redirect_url = urlencode(($_SERVER['QUERY_STRING'] ? uri_string() . '?' . $_SERVER['QUERY_STRING'] : uri_string()));
      if (!empty($redirect_url)) {
        redirect('signin?redirect_url=' . $redirect_url);
      } else {
        redirect('signin');
      }
      return;
    }
  }

  // Set redirect url in session (Not using)
  private function set_from_url() {
    if ($this->agent->is_browser()) {
      $from_url = urlencode(site_url() . ($_SERVER['QUERY_STRING'] ? uri_string() . '?' . $_SERVER['QUERY_STRING'] : uri_string()));
      $this->session->set_userdata('from_url', $from_url);
    }
  }

}

/**
 * For mobile API
 * 
 */
class MOBILE_Controller extends CI_Controller {

  public $mobile_session_id = NULL;
  public $mobile_current_user = array();
  public $response = array('status' => 0, 'message' => NULL, 'data' => NULL);

  public function __construct() {
    parent::__construct();

    // Setting timezone
    date_default_timezone_set('Asia/Calcutta');

    // Loading required libraries
    $this->load->library(array('user_session_mobile', 'crypt'));

    // Loading cache driver
    $this->load->driver('cache', array('adapter' => 'file'));

    // Setting session id
    if ($this->is_post()) {
      $this->mobile_session_id = (string) $this->input->post('session_id', TRUE);
    } else {
      $this->mobile_session_id = (string) $this->input->get('session_id', TRUE);
    }
  }

  // Clean the user inputs
  public function sanitize($data) {
    return trim(htmlentities(strip_tags($data), ENT_QUOTES, "UTF-8"));
  }

  // Check the request type is post
  public function is_post() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      return TRUE;
    } else {
      return FALSE;
    }
  }

}

class MOBILE_AUTH_Controller extends MOBILE_Controller {

  public function __construct() {
    parent::__construct();
    $signuser = $this->user_session_mobile->signuser($this->mobile_session_id);
    if (!empty($signuser)) {
      $this->mobile_current_user = $signuser;
    } else {
      $this->mobile_session_id = NULL;
      $this->mobile_current_user = NULL;
      $this->user_session_mobile->signout($this->mobile_session_id);
      $this->response['message'] = 'User authorization failed';
      die();
    }
  }

}

?>